package com.example.playerinfogame

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.view.View
import android.widget.GridLayout
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

// 卡片数据类：存储图片资源ID（用于匹配）和唯一标识
data class Card(
    val imageResId: Int,  // 图片资源ID（如R.drawable.img1）
    val id: Int,          // 唯一ID
    var isMatched: Boolean = false
)

class FlipCardGameActivity : AppCompatActivity() {

    private lateinit var gridLayout: GridLayout
    private lateinit var scoreTextView: TextView
    private lateinit var cards: List<Card>
    private var flippedCards: MutableList<Card> = mutableListOf()
    private var matches: Int = 0
    private var isProcessing: Boolean = false
    private var attemptCount: Int = 0
    private var startTime: Long = 0

    // 6对图片资源（共12张，每对资源ID相同，用于匹配判断）
    private val imagePairs = listOf(
        R.drawable.image1, R.drawable.image1,   // 第一对
        R.drawable.image2, R.drawable.image2,   // 第二对
        R.drawable.image3, R.drawable.image3,   // 第三对
        R.drawable.image4, R.drawable.image4,   // 第四对
        R.drawable.image5, R.drawable.image5,   // 第五对
        R.drawable.image6, R.drawable.image6    // 第六对
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_flip_card_game)

        gridLayout = findViewById(R.id.gridLayout)
        scoreTextView = findViewById(R.id.scoreTextView)
        initializeGame()
    }

    private fun initializeGame() {
        // 重置游戏数据
        attemptCount = 0
        matches = 0
        updateScoreDisplay()
        startTime = SystemClock.elapsedRealtime()

        // 打乱图片顺序
        val shuffledImages = imagePairs.shuffled()

        // 初始化卡片列表（用图片资源ID作为匹配依据）
        cards = shuffledImages.indices.map { index ->
            Card(
                imageResId = shuffledImages[index],  // 卡片对应的图片资源
                id = index
            )
        }

        // 配置网格
        gridLayout.columnCount = 4
        gridLayout.rowCount = 3  // 12张卡片 → 3行×4列
        gridLayout.removeAllViews()

        // 添加卡片视图（用ImageView显示图片）
        for (card in cards) {
            val cardView = ImageView(this).apply {
                // 初始显示卡片背面图片
                setImageResource(R.drawable.card_back)
                scaleType = ImageView.ScaleType.CENTER_CROP  // 图片适配方式
                layoutParams = GridLayout.LayoutParams().apply {
                    width = 200
                    height = 200
                    setMargins(8, 8, 8, 8)
                    columnSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f)
                    rowSpec = GridLayout.spec(GridLayout.UNDEFINED, 1f)
                }
                setOnClickListener { handleCardClick(card, this) }
                tag = card.id  // 用ID标记视图
            }
            gridLayout.addView(cardView)
        }
    }

    private fun handleCardClick(card: Card, view: ImageView) {
        // 过滤无效点击
        if (isProcessing || card.isMatched || flippedCards.contains(card)) {
            return
        }

        // 翻到正面：显示卡片对应的图片（隐藏了文字，直接显示图片）
        view.setImageResource(card.imageResId)
        flippedCards.add(card)

        // 两张卡片翻开后检查匹配
        if (flippedCards.size == 2) {
            attemptCount++
            updateScoreDisplay()
            checkForMatch()
        }
    }

    private fun checkForMatch() {
        isProcessing = true
        val firstCard = flippedCards[0]
        val secondCard = flippedCards[1]

        // 匹配判断：比较两张卡片的图片资源ID
        if (firstCard.imageResId == secondCard.imageResId) {
            // 匹配成功
            matches++
            firstCard.isMatched = true
            secondCard.isMatched = true
            flippedCards.clear()
            isProcessing = false

            // 游戏结束
            if (matches == 6) {  // 6对卡片全部匹配
                val endTime = SystemClock.elapsedRealtime()
                val usedTime = (endTime - startTime) / 1000
                val finalScore = Math.max(1000 - (attemptCount * 50) - (usedTime * 10), 0)
                Toast.makeText(
                    this,
                    "游戏结束！得分：$finalScore 分（尝试：$attemptCount 次，用时：$usedTime 秒）",
                    Toast.LENGTH_LONG
                ).show()
            }
        } else {
            // 匹配失败，1秒后翻回背面
            Handler(Looper.getMainLooper()).postDelayed({
                val firstView = findCardViewByID(firstCard.id) as ImageView?
                val secondView = findCardViewByID(secondCard.id) as ImageView?

                // 翻回背面图片
                firstView?.setImageResource(R.drawable.card_back)
                secondView?.setImageResource(R.drawable.card_back)

                flippedCards.clear()
                isProcessing = false
            }, 1000)
        }
    }

    // 根据卡片ID查找视图
    private fun findCardViewByID(cardId: Int): View? {
        for (i in 0 until gridLayout.childCount) {
            val child = gridLayout.getChildAt(i)
            if (child.tag == cardId) {
                return child
            }
        }
        return null
    }

    private fun updateScoreDisplay() {
        val currentTime = (SystemClock.elapsedRealtime() - startTime) / 1000
        val currentScore = Math.max(1000 - (attemptCount * 50) - (currentTime * 10), 0)
        scoreTextView.text = "尝试次数：$attemptCount | 当前得分：$currentScore"
    }
}